#
# Copyright 2009, Josef Kyrian <josef.kyrian@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import control
import g
from config import config
import select
import time
import Xlib.display
import Xlib.X
import pylirc
from PyQt4 import QtGui, QtCore, Qt
from dbglog import dbg


class IRWorker(QtCore.QThread):
	"""
	Thread listening to ir commands
	"""
	def run(self):
		try:
			lirchandle = pylirc.init("HTPCController", config.lircrcFilename, True)
			if (lirchandle):
				while (True):
					try:
						timeouted = select.select([lirchandle], [], [], 5) == ([], [], [])
					except Exception, e:
						print e
						continue
					#entry
					if (timeouted):
						dbg.log('IRRrec timed out')
						# IRRrec timed out
						pass
						#g.htpcController.setIrCommand('Mute')
						#self.emit(QtCore.SIGNAL('irEvent'))
					else:
						s = pylirc.nextcode()
				
						if (s):
							for code in s:
								dbg.log('New IR command received: %s', code)
								#print code
								g.htpcController.setIrCommand(code)
								self.emit(QtCore.SIGNAL('irEvent'))
								break
							#endfor
						#endif
					#endif
				#endwhile
			#endif
			
			# Clean up lirc
			pylirc.exit()
		except Exception, e:
			dbg.log('IRWorker exception: %s', str(e))
			raise
		#endtry
	#enddef
#enddef


def run():
	"""
	Runs listening
	"""
	irWorker = IRWorker()
	irWorker.start()
	
	return irWorker
#enddef
